package com.sihai.ehr.web.action.authority;

import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.sys.User;
import com.sihai.ehr.service.UserService;
import com.sihai.ehr.utils.MD5Util;
import com.sihai.ehr.web.AuthorityManager;
import com.sihai.ehr.web.action.EHRAction;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: wxn
 * @since: 12-7-17 下午22:27
 *
 * 登录相关Action
 */

@Results({
        @Result(name = "index", type = "redirect", location = "/index.xhtml"),
        @Result(name = "login", location = "login.jsp")
})
public class LoginAction extends EHRAction {
    @BeanInject
    private AuthorityManager authorityManager;
    
    private String message;

    @Action("/login")
    public String login() throws Exception {
        String account = getParameter("username");
        String password = getParameter("password");
        if(account == null && password == null){
            return "login";
        }

        AuthorityManager.LoginState state = authorityManager.loginCheck(account, password, ServletActionContext.getRequest(), ServletActionContext.getResponse());
        if(state == AuthorityManager.LoginState.SUCCESS){
            return "index";
        }else if(state == AuthorityManager.LoginState.NULLINPUT){
            message = "用户名或密码不为空";
        }else if(state == AuthorityManager.LoginState.ERRUSERORPWD){
            message = "用户名或密码错误";
        }
        return "login";
    }

    @Action("/logout")
    public String logout() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        //request.getSession().removeAttribute("current_user");
        request.getSession().invalidate();
        return "login";
    }

    @Action(value="/ajax/modify-password", results = { @Result(name = "success", type = "json", params = {"root", "message" }) })
    public String password() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        String name = (String)(request.getSession().getAttribute(AuthorityManager.user_name_session));
        if(StringUtils.equals(AuthorityManager.super_admin_name, name)){
            String password = getParameter("password");
            if(StringUtils.isNotBlank(password)){
                message = MD5Util.toMD5(password);
            }
        }
        return SUCCESS;
    }


    public String getMessage() {
        return message;
    }
}
